// pages/actual/index.js
import common from "../../common/compents.js";
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
import * as echarts from '../ec-canvas/echarts.js';
let App = getApp();
let oneComponent = null,
  myMap, myOptions;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    chartPower: true,
    goodsPower: true,
    checked: false,
    animationData: {},
    choose: 1,
    publish: 0,
    industy: 0,
    chartList: [],
    publishList: [],
    industyList: [],
    penPublishList: [],
    penIndustyList: [],
    goodsList: [],
    shareShow: false,
    ecChart: {
      lazyLoad: true //设置图表懒加载
    },
    chartSrc: '',
    realChecked:false,
  },
  // 获取实时数据
  getData() {
    let _token = wx.getStorageSync('token'),
      _obj = JSON.parse(wx.getStorageSync('currentOrganize')),
      that = this;
    wx.request({
      url: App.globalData.testApi + '/wechat/realtime/index',
      // url: "http://198.210.10.208:3000/mock/81/wechat/realtime/index",
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "token": _token
      },
      data: {
        supplier_id: _obj.supplier_id,
        organization_id: _obj.organization_id,
      },
      success(resapi) {
        if (resapi.data.code == 0) {
          let _arr = [],
            _arr1 = [],
            _set = [];
          _arr = resapi.data.data.supplier;
          _arr1 = resapi.data.data.all;
          if (that.data.choose == 1) {
            _set = _arr;
          } else {
            _set = _arr1;
          }
          // console.log(_set)
          that.setData({
            chartPower: true,
            publish: resapi.data.data.supplier.today.total,
            industy: resapi.data.data.all.today.total,
            publishList: _arr,
            industyList: _arr1,
            chartList: _set.yesterday.chart_data
          })
          that.initChart();
        } else if (resapi.data.code == 1008) {
          common.reLogin();
        } else if (resapi.data.code == 1009) {
          that.setData({
            chartPower: false
          });
        } else {
          Toast(resapi.data.message)
        }
      },
      fail(resapi) {
        console.log('失败', resapi);
        Toast("网络请求失败！");
      },
      complete(resapi) {
        wx.hideLoading();
      }
    })
  },
  // 获取商品排行
  getGoodsData() {
    let _token = wx.getStorageSync('token'),
      _obj = JSON.parse(wx.getStorageSync('currentOrganize')),
      that = this;
    wx.request({
      url: App.globalData.testApi + '/wechat/realtime/goodsrank',
      // url: "http://198.210.10.208:3000/mock/81/wechat/realtime/goodsrank",
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "token": _token
      },
      data: {
        supplier_id: _obj.supplier_id,
        organization_id: _obj.organization_id,
        type: that.data.choose == 1 ? 'supplier' : 'all',
        page: 1,
        page_size: 100,
        rank_type:that.data.realChecked?'sale_count':'sale_money'
      },
      success(resapi) {
        if (resapi.data.code == 0) {
          that.setData({
            goodsPower: true,
            goodsList: resapi.data.data
          })
        } else if (resapi.data.code == 1008) {
          common.reLogin();
        } else if (resapi.data.code == 1009) {
          that.setData({
            goodsPower: false
          });
        } else {
          Toast(resapi.data.message)
        }
      },
      fail(resapi) {
        console.log('失败', resapi);
        Toast("网络请求失败！");
      },
      complete(resapi) {
        wx.hideLoading();
      }
    })
  },
  initChart() {
    oneComponent = this.selectComponent('#actualCanvas');
    let that = this,
      _obj,
      _arr1 = [],
      _arr2 = [],
      _arr3 = [];
    if (this.data.choose == 1) {
      _obj = this.data.publishList;
    } else {
      _obj = this.data.industyList;
    }
    _obj.yesterday.chart_data.map((value, key) => {
      _arr1.push(value.time)
    })
    if (this.data.checked) {
      _obj.yesterday.chart_data.map((value, key) => {
        _arr2.push(value.per_ten_value)
      })
      _obj.today.chart_data.map((value, key) => {
        _arr3.push(value.per_ten_value)
      })
    } else {
      _obj.yesterday.chart_data.map((value, key) => {
        _arr2.push(value.value)
      })
      _obj.today.chart_data.map((value, key) => {
        _arr3.push(value.value)
      })
    }
    oneComponent.init((canvas, width, height, dpr) => {
      myMap = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      canvas.setChart(myMap);
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              show: false
            }
          },
          position: function (pos, params, dom, rect, size) {
            // 鼠标在左侧时 tooltip 显示到右侧，鼠标在右侧时 tooltip 显示到左侧。
            var obj = {
              top: '10%'
            };
            obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 10;
            return obj;
          },
          formatter(params) {
            console.log(params);
            let str = params[0].name + "\n";
            params.forEach((item) => {
              if (item.seriesName == '昨日' && params.length > 1) {
                str += item.seriesName + '：' + item.value + '\n';
              } else {
                str += item.seriesName + '：' + item.value;
              }
            })
            return str;
          }
        },
        color: ['#D1DDF6', '#5A8BEE'],
        legend: {
          show: false,
          data: ['昨日', '今日']
        },
        grid: {
          show: false,
          left: 5,
          right: 5,
          bottom: '5',
          top: 0,
          containLabel: false
        },
        xAxis: [{
          show: false,
          type: 'category',
          // boundaryGap: false,
          data: _arr1
        }],
        yAxis: [{
          show: false,
          type: 'value'
        }],
        series: [{
            name: '昨日',
            type: 'line',
            areaStyle: {},
            lineStyle: {
              width: 1
            },
            areaStyle: {

            },
            smooth: true,
            symbol: 'none',
            data: _arr2
          },
          {
            name: '今日',
            type: 'line',
            areaStyle: {},
            lineStyle: {
              width: 1
            },
            symbol: 'none',
            smooth: true,
            emphasis: {
              focus: 'series'
            },
            data: _arr3
          },
        ]
      };
      myOptions = option;
      myMap.setOption(option);
      return myMap
    });
  },
  dateChange(e) {
    this.setData({
      checked: e.detail,
    });
    let _arr = [];
    if (this.data.choose == 1) {
      _arr = this.data.publishList;
    } else {
      _arr = this.data.industyList;
    }
    this.setData({
      chartList: _arr.yesterday.chart_data
    })
    this.initChart();
  },
  realChange(e){
    this.setData({
      realChecked: e.detail,
    });
    this.getGoodsData();
  },
  changeChoose(e) {
    this.setData({
      choose: e.currentTarget.dataset.type,
    });
    wx.showLoading({
      mask: true
    })
    this.getGoodsData();
    let _arr = []
    if (this.data.choose == 1) {
      _arr = this.data.publishList;
    } else {
      _arr = this.data.industyList;
    }
    this.setData({
      chartList: _arr.yesterday.chart_data,
    })
    this.initChart();
  },
  renderCanvas() {
    this.setData({
      shareShow: false,
    })
    // Toast('该页面暂未开放画报功能！');
    // return
    wx.showLoading({
      mask: false,
      title: "数据画报生成中"
    })
    let that = this;
    let componentId = "#actualCanvas";
    let width, height, destWidth, destHeight;
    // 获取canvas高度
    if (this.data.chartList.length > 0) {
      const query = wx.createSelectorQuery()
      query.select(componentId).boundingClientRect()
      query.exec(function (rects) {
        rects.forEach(function (rect, n) {
          width = rect.width;
          height = rect.height;
          destWidth = rect.width;
          destHeight = rect.height;
          console.log(111, destHeight)
        })
        myMap.on("finished", () => {
          console.log("开始转换")
          console.log(555, that.selectComponent(componentId).canvasToTempFilePath)

          that.selectComponent(componentId).canvasToTempFilePath({
            x: 0,
            y: 0,
            width,
            height,
            // 截取canvas的宽度
            destWidth,
            // 截取canvas的高度    
            destHeight,
            success: res => {
              console.log("转换图片成功", res.tempFilePath)
              that.setData({
                chartSrc: res.tempFilePath,
              })
            },
            fail: res => {
              console.log("转换图片失败", res)
            },
            complete: res => {
              console.log("转换动作结束", res)
              // canvas 画图
              that.canvasHtml();
            }
          });
        });
        myMap.setOption(myOptions);
      })
    } else {
      // canvas 画图
      that.canvasHtml();
    }
  },
  canvasHtml() {
    this.widget = this.selectComponent('.widget');
    let wxml = '',
      that = this,
      _title = JSON.parse(wx.getStorageSync('currentOrganize')),
      _info = JSON.parse(wx.getStorageSync('initInfo'));
    wxml += `
      <view class="canvas-content">
        <view class="liubai"></view>`;
    wxml += `<view class="head">
        <text class="sjjb">实时数据</text>`
    if (_title.organization_name.length < 20) {
      wxml += `<text class="orgtitle">` + _title.organization_name + `</text>`;
    } else {
      wxml += `<text class="orgtitle">` + _title.organization_name.slice(0, 17) + '...' + `</text>`
    }
    wxml += `</view>`;
    // wxml += `<view class="account">
    //           <text class="you">由</text>
    //           <text class="mingzi">` + _info.account + `分享</text>
    //         </view>`;
    wxml += `<text class="zrxs">今日实时数据</text>`;
    if (this.data.chartPower) {
      // wxml += `<view class="actual-block">
      //         <view class="block">
      //           <text class="number">` + this.data.publish + `</text>
      //           <text class="text">本社销售指数</text>
      //         </view>
      //         <view class="block">
      //           <text class="number">` + this.data.industy + `</text>
      //           <text class="text">行业销售指数</text>
      //         </view>
      //       </view>`
      wxml += `<view class="actual-block">
                  <view class="actual-number">
                  <text class="yuan">￥</text>`
      if(this.data.publish < 10){
        wxml += `<text class="number">` + this.data.publish + `</text>`;
      }else if(this.data.publish < 100 && this.data.publish >= 10){
        wxml += `<text class="number width1">` + this.data.publish + `</text>`;
      }else if(this.data.publish < 1000 && this.data.publish >= 100){
        wxml += `<text class="number width2">` + this.data.publish + `</text>`;
      }else if(this.data.publish < 10000 && this.data.publish >= 1000){
        wxml += `<text class="number width2">` + this.data.publish + `</text>`;
      }else if(this.data.publish < 100000 && this.data.publish >= 10000){
        wxml += `<text class="number width3">` + this.data.publish + `</text>`;
      }else if(this.data.publish < 1000000 && this.data.publish >= 100000){
        wxml += `<text class="number width4">` + this.data.publish + `</text>`;
      }else if(this.data.publish < 10000000 && this.data.publish >= 1000000){
        wxml += `<text class="number width5">` + this.data.publish + `</text>`;
      }else if(this.data.publish < 100000000 && this.data.publish >= 10000000){
        wxml += `<text class="number width6">` + this.data.publish + `</text>`;
      }
      wxml += `</view>
                  <text class="actual-text">本社实时码洋</text>
                </view>`
      if (this.data.chartList.length > 0) {
        wxml += `<image class="chartimage" src="` + this.data.chartSrc + `"></image>`
      } else {
        wxml += `<text class="nodata">暂无图表数据</text>`
      }
    } else {
      wxml += `<text class="nodata nodata1">暂无权限</text>`
    }
    wxml += `<view class="greyblock"></view>`;
    wxml += `<text class="zrxs">实时销售排行</text>`;
    wxml += `<view class="three zs">
              <text class="tushu">图书信息</text>`;
    if(this.data.realChecked){
      wxml += `<text class="tushu">实时销量</text>`;
    }else{
      wxml += `<text class="tushu">实时码洋</text>`;
    }
    wxml += `</view>`;
    if (this.data.goodsPower) {
      if (this.data.goodsList.length > 0) {
        let goodsArr = this.data.goodsList.slice(0, 10);
        for (let i = 0; i < goodsArr.length; i++) {
          wxml += `<view class="three xiao">
                            <text class="paiming">` + goodsArr[i].rank + `</text>`;
          if (goodsArr[i].cover_pic) {
            let _src = goodsArr[i].cover_pic;
            if (_src.indexOf('https:') > -1) {
              _src = goodsArr[i].cover_pic;
            } else {
              _src = goodsArr[i].cover_pic.replace(/http/, 'https');
            }
            wxml += `<image class="cover" src="` + _src + `"></image>`
          } else {
            wxml += `<view class="no-image"></view>`
          }
          if (goodsArr[i].goods_name.length > 18) {
            wxml += `<text class="goodsname">` + goodsArr[i].goods_name.slice(0, 18) + '...' + `</text>`
          } else {
            wxml += `<text class="goodsname">` + goodsArr[i].goods_name + `</text>`
          }
          if(this.data.realChecked){
            wxml += `<text class="saletotal">` + goodsArr[i].sale_count + `</text>`
          }else{
            wxml += `<text class="saletotal">` + goodsArr[i].sale_amount + `</text>`
          }
          wxml += `</view>`
        }
      } else {
        wxml += `<text class="nodata nodata2">暂无数据</text>`
      }
    } else {
      wxml += `<text class="nodata nodata2">暂无权限</text>`
    }
    wxml += `<view class="zhichi">
              <image class="ercode" src="https://bodao.mhuoba.com/static/wximages/ercode.png"></image>
              <text class="jishu">博道出版数据实验室提供技术支持</text>
            </view>`;
    wxml += `</view>`;
    let style = {
      canvasContent: {
        backgroundColor: '#FFF',
        width: 375,
        height: 990,
        padding: 10,
      },
      liubai: {
        width: 355,
        height: 30
      },
      head: {
        width: 355,
        height: 23,
        flexDirection: 'row',
        alignItems: 'center'
      },
      sjjb: {
        width: 68,
        height: 23,
        fontSize: 16,
        color: '#07193F',
      },
      orgtitle: {
        width: 280,
        height: 18,
        fontSize: 12,
        color: '#07193F',
        marginLeft: 5
      },
      account: {
        width: 355,
        height: 18,
        fontSize: 12,
        color: '#7789AF',
        flexDirection: 'row',
        marginTop: 10
      },
      you: {
        width: 12,
        height: 18,
      },
      mingzi: {
        width: 335,
        height: 18,
      },
      zrxs: {
        width: 355,
        height: 20,
        fontSize: 14,
        color: '#07193F',
        marginTop: 15
      },
      actualBlock: {
        width: 355,
        height: 64,
        borderRadius: 5,
        backgroundColor: '#F4F7FD',
        paddingTop:10,
        // flexDirection: 'row',
        // justifyContent: 'space-between',
        marginTop: 5
      },
      actualNumber:{
        width:355,
        height:26,
        flexDirection: 'row',
        justifyContent: 'center',
      },
      yuan:{
        width:13,
        height:18,
        fontSize:12,
        marginTop:5,
        color:'#07193F',
      },
      number: {
        width:12,
        height: 26,
        fontSize: 18,
        color: '#07193F',
        textAlign:'center',
      },
      actualText: {
        width: 355,
        height: 18,
        fontSize: 12,
        color: '#7789AF',
        // marginTop:5,
        textAlign: 'center'
      },
      width1:{
        width:22
      },
      width2:{
        width:32
      },
      width3:{
        width:54
      },
      width4:{
        width:64
      },
      width5:{
        width:74
      },
      width6:{
        width:86
      },
      chartimage: {
        width: 355,
        height: 110,
        marginTop: 15,
        marginBottom: 15
      },
      greyblock: {
        width: 375,
        height: 4,
        backgroundColor: '#F4F7FD',
        marginLeft: -10
      },
      three: {
        width: 355,
        height: 26,
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 2
      },
      zs: {
        justifyContent: 'space-between'
      },
      tushu: {
        width: 48,
        height: 18,
        fontSize: 12,
        color: '#7789AF'
      },
      xiao: {
        height: 39,
        marginBottom: 10
      },
      paiming: {
        width: 32,
        height: 18,
        fontSize: 12,
        color: '#07193F'
      },
      cover: {
        width: 36,
        height: 36,
      },
      noImage: {
        width: 36,
        height: 36,
        backgroundColor: '#D1DDF6'
      },
      goodsname: {
        width: 210,
        height: 20,
        fontSize: 12,
        color: '#07193F',
        flexWrap: 'wrap',
        marginLeft: 5
      },
      saletotal: {
        width: 67,
        height: 20,
        fontSize: 14,
        color: '#7789AF',
        textAlign: 'right'
      },
      nodata: {
        width: 355,
        height: 110,
        lineHeight: 110,
        color: '#7789AF',
        fontSize: 12,
        textAlign: 'center',
      },
      nodata1: {
        height: 200,
        lineHeight: 200,
      },
      nodata2: {
        height: 400,
        lineHeight: 400,
      },
      zhichi: {
        width: 355,
        height: 78,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: "center",
        marginTop: 20
      },
      ercode: {
        width: 48,
        height: 48,
      },
      jishu: {
        width: 180,
        height: 18,
        color: '#07193F',
        fontSize: 12,
        marginLeft: 15
      },
    }
    console.log(22, {
      wxml,
      style
    });
    const p1 = this.widget.renderToCanvas({
      wxml,
      style
    });
    p1.then((res) => {
      // console.log('canvasContent', res)
      this.canvasContent = res
      wx.hideLoading();
      Dialog.confirm({
          title: '',
          message: '画报生成成功，是否保存至手机相册',
        })
        .then(() => {
          // on confirm
          that.extraImage();
        })
        .catch(() => {
          // on cancel
        });
    })
  },
  extraImage() {
    let that = this;
    const p2 = this.widget.canvasToTempFilePath();
    p2.then(res => {
      console.log('最后1', res.tempFilePath)
      that.setData({
        src: res.tempFilePath,
        // width: this.canvasContent.layoutBox.width,
        // height: this.canvasContent.layoutBox.height
      })
      wx.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success(res) {
          console.log('保存图片成功', res)
          Toast('成功保存至手机相册！')
        },
        fail(res) {
          console.log('保存图片失败', res)
          Toast('保存至手机相册失败！')
        },
        complete(res) {
          console.log('保存图片动作结束', res)
          wx.hideLoading();
        }
      })
    })
  },
  // 点击商品封面
  onClick(e) {
    // console.log(e.currentTarget.dataset.id)
    common.toDetail(e.currentTarget.dataset.id)
  },
  touchMove() {
    // console.log(1);
    var animation = wx.createAnimation({
      duration: 500
    })
    animation.translateX('80rpx').step();
    this.setData({
      animationData: animation.export()
    });
  },
  touchCancel() {
    // console.log(2);
    var animation = wx.createAnimation({
      duration: 500
    })
    animation.translateX('0').step();
    this.setData({
      animationData: animation.export()
    });
  },
  touchEnd() {
    var animation = wx.createAnimation({
      duration: 500
    })
    animation.translateX('0').step();
    this.setData({
      animationData: animation.export()
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // console.log(222,options)
    if (wx.getStorageSync("token")) {
      let _title = JSON.parse(wx.getStorageSync('currentOrganize'));
      wx.setNavigationBarTitle({
        title: _title.organization_name,
      })
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 300
      })
      wx.showLoading({
        mask: true
      })
      this.getData();
      this.getGoodsData();
    } else {
      wx.reLaunch({
        url: '/pages/login/index'
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.hideLoading();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  onPageScroll: function (e) {
    let that = this;
    var animation = wx.createAnimation({
      duration: 500
    })
    animation.translateX('80rpx').step();
    this.setData({
      animationData: animation.export()
    });
    setTimeout(() => {
      var animation = wx.createAnimation({
        duration: 500
      })
      animation.translateX('0').step();
      this.setData({
        animationData: animation.export()
      });
    }, 2000)
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "博道出版数据实验室"
    }
  }
})